<template>
  <div class="split-panel-container">
    <div class="layout-container">

      <!--      左侧面板-->
      <div :style="{ width: `${leftWidth}%` }" class="panel-left">
        <el-tree
            v-model="searchForm.category"
            :data="treeCategories"
            :default-expanded-keys="['0']"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            class="custom-tree"
            node-key="id"
            :current-node-key="currentNodeKey"
            :highlight-current="true"
            @node-click="handleCategorySelect"
            @node-contextmenu="showContextMenu"
        />
      </div>

      <!--      分割栏-->
      <div class="resize-handle" @mousedown="startResize">
        <div class="handle-icon"></div>
      </div>

      <!--    拖动预览线-->
      <div v-if="isResizing" :style="{ left: `${tempLeftWidth}%` }" class="resize-preview-line">
      </div>

      <!--右侧列表-->
      <div :style="{ width: `${rightWidth}%` }" class="panel-right right-content">
        <ProtocolList ref="protocolListRef"
                      :show-btn="showBtn"
                      @select="handleProtocolSelect"
        />
      </div>


    </div>
  </div>

  <!-- 分类右键菜单 -->
  <div v-if="contextMenuVisible"
       :style="{ position: 'fixed', left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px', zIndex: 1000, background: '#fff', border: '1px solid #ccc', borderRadius: '4px', boxShadow: '2px 2px 10px rgba(0,0,0,0.1)' }">
    <div style="padding: 8px 12px; cursor: pointer;" @click="renameCategory">编辑分类</div>
    <div style="padding: 8px 12px; cursor: pointer; color: #6894fb;" @click="showAddCategory">新增分类</div>
    <div style="padding: 8px 12px; cursor: pointer; color: #f56c6c;" @click="deleteCategory">删除分类</div>
  </div>

  <!-- 编辑分类对话框 -->
  <el-dialog v-model="renameDialogVisible" title="编辑分类" width="300px">
    <el-form :model="renameCategoryForm">
      <el-form-item :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]" label="分类名称"
                    prop="name">
        <el-input v-model="renameCategoryForm.name" placeholder="分类名称"/>
      </el-form-item>
      <el-form-item label="父分类" prop="pid">
        <el-tree-select
            v-model="renameCategoryForm.pid"
            :data="treeCategories"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly=true
            placeholder="选择父分类"
            style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="renameDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmRename">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新增分类对话框 -->
  <el-dialog v-model="showAddCategoryDialog" title="添加新分类" width="300px">
    <el-form :model="newCategory">
      <el-form-item :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]" label="分类名称"
                    prop="name">
        <el-input v-model="newCategory.name" placeholder="请输入新分类名称"/>
      </el-form-item>
      <el-form-item label="父分类" prop="pid">
        <el-tree-select
            v-model="newCategory.pid"
            :data="treeCategories"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly=true
            placeholder="选择父分类"
            style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddCategoryDialog = false">取消</el-button>
      <el-button type="primary" @click="addCategory">确定</el-button>
    </template>
  </el-dialog>

</template>


<script lang="ts" setup>

import {searchForm, treeCategories, updateCategoryList} from "@/views/ToolLibs/ProtocolViewer/protocol";
import {defineEmits, defineProps, onMounted, onUnmounted, ref, withDefaults} from "vue";
import ProtocolList from "@/views/ToolLibs/ProtocolViewer/components/ProtocolList.vue";
import {deleteProtocolCategoryById, saveOrUpdateProtocolCategory} from "@/api/toolLibs/protocolLib";
import {message} from "@/utils/ElmessasgeUtils";
import {ElTreeSelect} from "element-plus";


const props = withDefaults(
    defineProps<{
      showBtn: boolean
    }>(),
    {
      showBtn: true
    })


const protocolListRef = ref()
const showBtn = ref(props.showBtn);

const defaultLeftWidth = 13
const minLeftWidth = 10      //左侧最小宽度
const minRightWidth = 50     //右侧最小宽度

const emit = defineEmits<{
  (e: 'select', protocolId: string): void
}>()

const leftWidth = ref(defaultLeftWidth)
const rightWidth = ref(100 - defaultLeftWidth)
const tempLeftWidth = ref(defaultLeftWidth) // 临时宽度，用于拖动预览

const isResizing = ref(false)


// 分类点击事件
function handleCategorySelect(key: any, node: any) {
  if (!protocolListRef.value) {
    console.warn('ProtocolList 组件引用不存在')
    return
  }

  const allChildrenValues = getAllChildrenIds(node);

  // 包含当前
  allChildrenValues.push(key.id)

  searchForm.categories = allChildrenValues
  searchForm.category = key.id

  selectedCategoryItem.value = key
  // 更新当前节点key，用于高亮显示
  currentNodeKey.value = key.id

  const instance = protocolListRef.value

  // 尝试调用 handleSearch 方法
  if (typeof instance.handleSearch === 'function') {
    instance.handleSearch()
    return
  }
}

// 处理协议选择
function handleProtocolSelect(protocolId: string) {
  emit('select', protocolId)
}

// 递归获取所有子节点的值
function getAllChildrenIds(node: any) {
  let result: any = [];
  // 检查是否存在子节点
  if (node.childNodes && node.childNodes.length > 0) {
    node.childNodes.forEach((child: any) => {
      // 将子节点id加入结果数组
      if (child.data && child.data.id) {
        result.push(child.data.id);
      }
      // 递归获取子节点的子节点id
      result = result.concat(getAllChildrenIds(child));
    });
  }
  return result;
}


// -----------------右键菜单相关-------------------
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({x: 0, y: 0})
const selectedCategoryItem = ref<any>(
    {id: '0', name: ''}
)

// 当前选中节点的key，用于高亮显示
const currentNodeKey = ref(searchForm.category)
const renameDialogVisible = ref(false)

// 编辑分类表单
const renameCategoryForm = ref<{ id: number | null, name: string, pid: number | null }>({id: null, name: '', pid: null})

// 显示右键菜单
function showContextMenu(event: any, category: any) {
  // 阻止默认右键菜单
  event.preventDefault();
  // 不显示"全部"分类的右键菜单
  if (category.id === '0') return;
  contextMenuPosition.value = {x: event.clientX, y: event.clientY};

  selectedCategoryItem.value = category;
  contextMenuVisible.value = true;
  // 点击其他区域关闭菜单
  document.addEventListener('click', closeContextMenu);
}

// 关闭右键菜单
function closeContextMenu() {
  contextMenuVisible.value = false;
  document.removeEventListener('click', closeContextMenu);
}


// 编辑分类
function renameCategory() {
  renameCategoryForm.value.name = selectedCategoryItem.value.name;
  renameCategoryForm.value.id = selectedCategoryItem.value.id;
  renameCategoryForm.value.pid = selectedCategoryItem.value.pid;

  renameDialogVisible.value = true;
  contextMenuVisible.value = false;
}

// 编辑分类
function confirmRename() {
  saveOrUpdateProtocolCategory({
    id: renameCategoryForm.value.id,
    pid: renameCategoryForm.value.pid,
    name: renameCategoryForm.value.name
  }).then((res: any) => {
    if (res.data.code == 200) {
      message("编辑分类成功")
      updateCategoryList();
      protocolListRef.value.handleSearch()

      // 保持当前节点高亮
      currentNodeKey.value = renameCategoryForm.value.id

      renameDialogVisible.value = false;
    } else {
      message("编辑分类失败", 'error')
    }
  })

}

// 新增分类
const showAddCategoryDialog = ref(false)
const newCategory = ref({name: '', pid: '0'})

function showAddCategory() {
  newCategory.value.pid = searchForm.category
  showAddCategoryDialog.value = true;
}

async function addCategory() {
  let res: any = await saveOrUpdateProtocolCategory(newCategory.value)
  if (res.data.code == 200) {
    message("新增分类成功")
    showAddCategoryDialog.value = false
    await updateCategoryList()
  } else {
    message("新增分类失败: " + res.data.msg, 'error');
  }
}

// 删除分类
function deleteCategory() {
  const deletedId = selectedCategoryItem.value.id

  deleteProtocolCategoryById(deletedId).then((res: any) => {
    if (res.data.code == 200) {
      message("删除分类成功")
      contextMenuVisible.value = false;
      updateCategoryList();

      // 如果删除的是当前选中的节点，重置选中状态
      if (currentNodeKey.value === deletedId) {
        currentNodeKey.value = '0'
        searchForm.category = '0'
        searchForm.categories = []

        // 调用搜索方法刷新列表
        if (protocolListRef.value && typeof protocolListRef.value.handleSearch === 'function') {
          protocolListRef.value.handleSearch()
        }
      }
    } else {
      message("删除分类失败: " + res.data.msg, 'error')
    }
  })
}


/**
 *  --------------------------------- 布局 分割线相关 -------------------------
 */
// 开始拖动分割线
const startResize = (e: MouseEvent) => {

  isResizing.value = true
  document.body.style.cursor = 'col-resize'
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  e.preventDefault() // 阻止默认行为，防止选中内容
}


// 处理左右面板尺寸
const handleResize = (e: MouseEvent) => {
  const container = document.querySelector('.split-panel-container') as HTMLElement
  const containerRect = container.getBoundingClientRect()
  const containerWidth = containerRect.width
  // 计算鼠标在容器中的相对位置百分比
  let mouseX = e.clientX - containerRect.left
  let newLeftWidth = (mouseX / containerWidth) * 100
  // 应用最小宽度限制
  if (newLeftWidth < minLeftWidth) newLeftWidth = minLeftWidth
  if (newLeftWidth > 100 - minRightWidth) newLeftWidth = 100 - minRightWidth
  // 只更新临时宽度，用于预览线显示
  tempLeftWidth.value = newLeftWidth
}

// 停止拖动分割线
const stopResize = () => {
  isResizing.value = false
  document.body.style.cursor = ''
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  // 放手时，将临时宽度应用到实际宽度
  leftWidth.value = tempLeftWidth.value
  rightWidth.value = 100 - leftWidth.value
}

// 初始化左右布局
onMounted(() => {
  // 初始化宽度
  leftWidth.value = defaultLeftWidth
  rightWidth.value = 100 - defaultLeftWidth
})

onUnmounted(() => {
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
})


onMounted(async () => {
  await updateCategoryList();
})
</script>

<style lang="scss" scoped>
.split-panel-container {
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 300px;
  overflow: hidden;

  .layout-container {
    display: flex;
    height: 100%;
    position: relative;
  }

  .panel-left, .panel-right {
    position: relative;
    overflow: hidden; /* 修改为hidden，避免整个面板滚动 */
    transition: width 0.3s ease, background-color 0.3s ease;
    /* 自定义滚动条 */
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(150, 150, 150, 0.5);
      border-radius: 4px;
      transition: background 0.2s;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: rgba(100, 100, 100, 0.7);
    }
  }

  .panel-left {
    /* 关键调整：将左侧面板的右侧padding设置为负数，使内容可以扩展到滚动条区域 */
    padding-right: -8px;
    margin-right: 1px; /* 补偿padding，保持整体宽度不变 */
    /* 让左侧面板的滚动条与分割线重叠 */
    &::-webkit-scrollbar {
      position: absolute;
      right: 0;
      width: 8px; /* 滚动条宽度 */
    }

    /* 自定义树样式 */
    .custom-tree {
      padding: 10px;
      /* 增强当前选中节点的高亮样式 */
      :deep(.el-tree-node.is-current > .el-tree-node__content) {
        background-color: #94bee9 !important;
        color: white !important;
        font-weight: 600;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(165, 210, 255, 0.3);
      }

      /* 鼠标悬停样式 */
      :deep(.el-tree-node__content:hover) {
        background-color: #b8e2fd !important;
        border-radius: 4px;
      }

      /* 节点内容间距调整 */
      :deep(.el-tree-node__content) {
        padding: 6px 12px !important;
        transition: all 0.2s ease;
      }
    }
  }

  .resize-handle {
    position: relative;
    width: 2px;
    background-color: #f0f0f0;
    cursor: col-resize;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    z-index: 20; /* 确保分割线在最上层 */
    /* 鼠标悬停和拖动时的样式 */
    &:hover, &:active {
      background-color: #e0e0e0;
    }

    .handle-icon {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 1px;
      height: 30px;
      background-color: #ccc;

      &::before, &::after {
        content: '';
        position: absolute;
        width: 1px;
        height: 30px;
        background-color: #ccc;
      }

      &::before {
        left: -2px;
      }

      &::after {
        left: 2px;
      }
    }
  }

  // 拖动预览线样式
  .resize-preview-line {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 2px;
    background-color: #409eff;
    z-index: 100; /* 确保预览线在最上层 */
    cursor: col-resize;
    box-shadow: 0 0 4px rgba(64, 158, 255, 0.5);
  }

  .panel-content {
    padding: 1px;
    height: 100%; /* 修改为固定高度 */
    display: flex;
    flex-direction: column;
    /* 添加顶部过渡 */
    border-top: 2px solid transparent;
    border-image: linear-gradient(to right, #f0f0f0, transparent) 1;
  }

  .default-content {
    padding: 2px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin: 10px;
  }

  // Tab相关样式
  .tab-container {
    display: flex;
    flex-direction: row;
    height: 100%;
    position: relative;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  // 左侧竖向按钮样式
  .vertical-tab-buttons {
    display: flex;
    flex-direction: column;
    width: 24px; /* 一个文字的宽度 */
    background-color: #f5f7fa;
    border-right: 1px solid #e4e7ed;
    z-index: 10;
    transition: all 0.3s ease;
    padding: 4px 0;
  }

  // 独立的折叠图标按钮样式
  .collapse-toggle-button {
    width: 24px; /* 与下方按钮相同宽度 */
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #606266;
    margin: 4px 0;
    border-radius: 4px;
    transition: all 0.3s ease;
    background-color: transparent;
    border: none;

    &:hover {
      background-color: #f0f2f5;
      color: #303133;
    }
  }

  .vertical-tab-button {
    writing-mode: vertical-rl;
    text-orientation: mixed;
    padding: 12px 4px;
    background: none;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
    color: #606266;
    border-right: 3px solid transparent;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    position: relative;

    &:hover {
      color: #303133;
      background-color: #f0f2f5;
    }

    &.active {
      color: #67c23a;
      border-right-color: #67c23a;
      background-color: #f0f9eb;
      font-weight: 500;
    }
  }

  .tab-content-wrapper {
    flex: 1;
    min-width: 200px;
    position: relative;
    padding: 5px 0;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    opacity: 1;
    transform: translateX(0);
  }

  .tab-content {
    display: block;
    min-width: 200px;
    padding: 1px 0;
    // 确保内容可见
    opacity: 1;
    visibility: visible;
  }
}


.toolbar-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  background-color: #f5f5f5;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
  outline: none;

  &:hover {
    background-color: #ecf5ff;
    color: #409eff;
  }

  &.add-connection:hover {
    background-color: #e3f2fd;
    color: #1976d2;
  }

  &.new-group:hover {
    background-color: #e8f5e9;
    color: #388e3c;
  }

  &.refresh:hover {
    background-color: #fff3e0;
    color: #f57c00;
  }

  .toolbar-icon {
    width: 18px;
    height: 18px;
    object-fit: contain;
  }
}

// 右键菜单样式
.context-menu {
  position: fixed;
  background-color: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 100px;
  padding: 4px 0;
}

// 右侧内容区域样式
.right-content {
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

.full-height-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-tabs__header) {
    margin: 0;
    border-bottom: 1px solid #e4e7ed;
  }

  :deep(.el-tabs__content) {
    flex: 1;
    overflow: hidden;
  }
}

</style>